<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:widget="http://www.netvibes.com/ns/">
    <head>

         <!-- Application Metas -->
        <title>Uday's Quick Stock Watch</title>
        <meta name="author" content="Uday Kumar Pyda" />
        <meta name="description" content="A simple Stock Quotes and Portfolio tracking module. Works for over 30 international markets - Argentina, Australia, Austria, Belgium, Brazil, Canada, China, Denmark, Egypt, France, Germany, Hong Kong, India, Israel, Italy, Japan, Jakarta, Korea, Malaysia, Mexico, Netherlands, New Zealand, Norway, Singapore, Spain, Sweden, Switzerland, Taiwan, Turkey, UK, United States and more.. You can watch the up and down ticks of your favorite stocks and monitor your portfolio at desired intervals (Data provided by Yahoo! Finance)" />
        <meta http-equiv="Content-Script-Type" content="text/javascript" />

        <!-- Application Standalone emulation files -->
        <link rel="stylesheet" type="text/css"
            href="http://uwa.netvibes.com/lib/c/UWA/assets/css/standalone.css" />
        <script type="text/javascript"
            src="http://uwa.netvibes.com/lib/c/UWA/js/UWA_Standalone_Alone.js"></script>
		
        <!-- Application Preferences -->
        <widget:preferences>
        	<widget:preference name="title" type="text" label="Title" defaultValue="Uday's Quick Stock Watch" />
        	<widget:preference name="flashing" type="list" label="Highlighting" defaultValue="0" onchange="refresh">
        		<option value="1" label="On"/>
        		<option value="0" label="Off"/>
        	</widget:preference>
		    <widget:preference name="refreshrate" type="list" label="Refresh Rate" defaultValue="300" onchange="refresh">
        		<option value="-1" label="No Refresh"/>
        		<option value="30" label="30 seconds"/>
        		<option value="60" label="1 minute"/>
        		<option value="300" label="5 minutes"/>
        	</widget:preference>
        	<widget:preference name="showchart" type="list" label="Show Charts" defaultValue="1" onchange="refresh">
        		<option value="0" label="None"/>
        		<option value="1" label="1 day"/>
        		<option value="5" label="5 day"/>
        		<option value="90" label="3 month"/>
        		<option value="180" label="6 month"/>
        		<option value="365" label="1 year"/>
        	</widget:preference>
		    <widget:preference name="showname" type="list" label="Stock Name" defaultValue="1" onchange="refresh">
		    	<option value="1" label="Show"/>
    			<option value="0" label="Hide"/>
		    </widget:preference>
		    <widget:preference name="tickers" type="hidden" defaultValue="^GSPC,^IXIC" onchange="refresh"/>
		    <widget:preference name="shownews" type="hidden" defaultValue="0" onchange="refresh"/>
		    <widget:preference name="showstrength" type="hidden" defaultValue="0" onchange="refresh"/>
		    
		    <widget:preference name="promo1" type="hidden" label="Welcome Message" defaultValue="0" />  
        	
        </widget:preferences>
        
        <!-- Application JavaScript Source -->
        <style type="text/css">
		  a { color:#0000DD;}
		  a:visited { color:#0000DD;}  
		</style>
		<script type="text/javascript">
        //<![CDATA[
			var showname, flashing, showchart, refreshrate, showNews, showStrength, strTickers, stockTickers;
			var baseURL = "http://download.finance.yahoo.com/d?s=";
			var sortcol = 'symbol';
			var cURL = "http://ichart.finance.yahoo.com/t?s=";
			var newDate = new Date().getTime();
			var reloadId = "0";
			var newsReloadId = "0";
			var newsURL = 'http://finance.yahoo.com/rss/headline?s=';
			var newsItemArray = new Array();
			var staticImgUrl = "http://udaysasi-gadgets.googlecode.com/svn/trunk/delete.gif"; 
			
			function initWidget() {
				showname = widget.getInt("showname");
				flashing = widget.getInt("flashing");
				showchart = widget.getInt("showchart");
				refreshrate = widget.getInt("refreshrate");
				showNews = widget.getInt("shownews");
				showStrength = widget.getInt("showstrength");
				strTickers = widget.getValue("tickers");
				
				strTickers = convertToNewFormat(strTickers);
				stockTickers = convertToArray2(strTickers);
				
				stockTickers = sortArray(stockTickers);
				
				if(refreshrate!=-1 && refreshrate<30) {
					refreshrate = 30;
					widget.setValue("refreshrate", 30);
				}
				if (showchart == 5) {
				    cURL = "http://ichart.finance.yahoo.com/v?s=";
				}
				else if (showchart == 90) {
				    cURL = "http://ichart.finance.yahoo.com/z?t=3m&l=off&z=b&s=";
				}
				else if (showchart == 180) {
				    cURL = "http://ichart.finance.yahoo.com/z?t=6m&l=off&z=b&s=";
				}
				else if (showchart == 365) {
				    cURL = "http://ichart.finance.yahoo.com/z?t=1y&l=off&z=b&s=";
				}
				
				var title = widget.getValue("title");
				if(title!='' && title!="Uday's Quick Stock Watch")
					title += ' - Quick Stock Watch';
				
				widget.setTitle(title);
				console.log(widget.environment.name);
				if(widget.environment.name=='frame') {
					
					var adContent = widget.getElement("#adContent");
					if(adContent!=null)
						adContent.destroy();
				}
			}
			
			function NewsItem(title, link, time){ this.title = title;this.link = link;this.time = time;}
			
			function gel(id) {
				return widget.getElement('#'+id);	
			}
			
			function getAlphaNumericName(txtString)
			{
				txtString = txtString.toLowerCase();
				txtString = txtString.replace(/[^a-zA-Z 0-9]+/g,"");
				return txtString;
			}

			function callNewsServer()
			{ 
				var feedURL = ''; 
				var newDate = new Date().getTime(); 
				feedURL = newsURL+convertToString(stockTickers) + "&nocache="+newDate;
				/*
				var params = params || {};
				params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;
				params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 60;
				gadgets.io.makeRequest(feedURL, processNewsResponse, params);
				*/
				UWA.Data.getXml(feedURL, processNewsResponse);
			}
			function processNewsResponse(r)
			{
				try 
				{ 
					var itemList = r.getElementsByTagName("item");	
					newsItemArray = new Array(); 
					for (var i = 0; i < itemList.length ; i++)  
					{ 
						if(i>=4) 
							break; 
						var nodeList = itemList.item(i).childNodes; 
						var title = '', link='', diff; 
						for (var j = 0; j < nodeList.length ; j++)  
						{ 
							var node = nodeList.item(j); 
							if (node.nodeName == "title") 
							{ 
								title = node.firstChild.nodeValue; 
							} 
							if (node.nodeName == "link") 
							{ 
								link = node.firstChild.nodeValue; 
							}
							if (node.nodeName == "pubDate") 
							{ 
								var newdate = new Date(node.firstChild.nodeValue);
								var curdate = new Date(new Date().toGMTString());
								diff = (curdate-newdate)/1000;
								if(isNaN(diff))
									diff = '';
								else if(diff<60)
									diff = ' - '+diff+' sec ago';
								else if(diff<60*60)
									diff = ' - '+Math.floor(diff/60) + ' min ago';
								else if(diff<60*60*24)
									diff = ' - '+Math.floor((diff/3600))+' hr '+Math.floor((diff%3600)/60)+' min ago';
								else{
									var days = Math.floor((diff/86400));
									diff = ' - '+days+(days>1?' days ago':' day ago');
								}
							}				
						} 
						newsItemArray = newsItemArray.concat(new NewsItem(title, link, diff)); 
					} 
					
					displayNewsContent();	 
				}
				catch(e){ }   
				
				newsReloadId = setTimeout(callNewsServer, 300000);	
			}
			
			function displayNewsContent()
			{
				var header = ''; 
				var footer = ''; 
				var contentText = '';  
				if(newsItemArray.length==0) 
					contentText = 'No news available for stocks in your watchlist'; 
				for (i=0;i<newsItemArray.length;i++) 
					contentText+='<li><a href="'+newsItemArray[i].link+'" target="newsT"><font size="-1">'+newsItemArray[i].title+'</font></a><font size="-1" color="#AAAAAA">'+newsItemArray[i].time+'</font></li>'; 		
				
				gel('newsContent').setHTML(header+contentText+footer);		
			}
			
			showNewsContent = function() {
				clearTimeout(newsReloadId);
				if(showNews==0)
				{
					gel('newsContent').setHTML('Loading news on stocks in your watch list..');
					gel('newsContent').setStyle('display', '');
					gel('newsHorLine').setStyle('display', '');
					callNewsServer();
					showNews = 1;		
					widget.setValue("shownews", 1);
				}
				else
				{
					gel('newsContent').setStyle('display', 'none');		
					gel('newsContent').setHTML('');		
					gel('newsHorLine').setStyle('display', 'none');		
					showNews = 0;
					widget.setValue("shownews", 0);
				}
			}
			showStrengthContent = function() {
				if(showStrength==0)
				{
					gel('strengthContent').setStyle('display', '');
					gel('strHorLine').setStyle('display', '');
					showStrength = 1;		
					widget.setValue("showstrength", 1);
				}
				else
				{
					gel('strengthContent').setStyle('display', 'none');		
					gel('strHorLine').setStyle('display', 'none');		
					showStrength = 0;
					widget.setValue("showstrength", 0);
				}
			}
			
			function convertToString(arr) {
			    var returnString = "";
			    for (var g = 0; g < arr.length; g++) {
			        returnString += arr[g].symbol + ",";
			    }
			    return returnString;
			}
			
			function convertToString2(arr) {
			    var returnString = "";
			    for (var g = 0; g < arr.length; g++) {
			        returnString += arr[g].symbol + "|" + arr[g].numshares + "|" + arr[g].buyprice + ",";
			    }
			    return returnString;	
			}
			
			function convertToArray(str) {
			    var returnArray = new Array();
			    str = str.replace(/ /g, ",");
			    var ticks = str.split(",");
			    ticks.sort();
			    for (var d = 0; d < ticks.length; d++) {
			        var curTicker = ticks[d];
			        curTicker = curTicker.toUpperCase();
			        if (curTicker == "") {
			            continue;
			        }
			        returnArray.push(new StockTicker(curTicker, "Loading..", "0", "0", "(0%)"));
			    }
			    return returnArray;
			}
			
			function convertToNewFormat(str) {
				if(str.indexOf("|")!=-1)
					return str;
			    var returnString = "";
			    str = str.replace(/ /g, ",");
			    var ticks = str.split(",");
			    ticks.sort();
			    for (var d = 0; d < ticks.length; d++) {
			        var curTicker = ticks[d];
			        curTicker = curTicker.toUpperCase();
			        if (curTicker == "") {
			            continue;
			        }
			        returnString += curTicker + "|0|0.00,";        
			    }
			    return returnString;		
			}
			
			function convertToArray2(str) {
			    var returnArray = new Array();
			    str = str.replace(/ /g, ",");
			    var ticks = str.split(",");
			    ticks.sort();
			    for (var d = 0; d < ticks.length; d++) {
			        var curTicker = ticks[d];
			        curTicker = curTicker.toUpperCase();
			        var curTickerData = curTicker.split("|");
			        if (curTickerData[0] == "") {
			            continue;
			        }
			        returnArray.push(new StockTicker(curTickerData[0], "Loading..", "0", "0", "(0%)", curTickerData[1], curTickerData[2]));
			    }
			    return returnArray;
			}
			
			function StockTicker(symbol, name, price, change, percent, numshares, buyprice) {
			    this.symbol = symbol;
			    this.name = name;
			    this.price = price;
			    this.change = change;
			    this.percent = percent;
			    this.numshares = numshares;
			    this.buyprice = buyprice;
			}
			function getSymbolArray() {
			    var symbolArray = new Array();
			    for (u = 0; u < stockTickers.length; u++) {
			        symbolArray = symbolArray.concat(stockTickers[u].symbol);
			    }
			    return symbolArray;
			}
			
			/*
			function getDowData() {
				var nameSpan = gel("^DJINameSpan");
				var priceSpan = gel("^DJIPriceSpan");
				var changeSpan = gel("^DJIChangeSpan");
				var percentSpan = gel("^DJIPercentSpan");
				var row = gel("^DJIRow");
				if(!nameSpan)
					return;
				var quote = '';
				try {
				 	quote = new google.finance.Quote();
				} catch(e) {
					var pos = getPosition("^DJI");
					setName(pos, "Dow(Not supported)");
					nameSpan.setHTML("Dow(Not supported)");
					row.style.color = "#888888";
					row.style.textDecoration="line-through";
					return;
				}		
				quote.getQuotes([".DJI"]);	
				quote.addListener(function(data) {	
					nameSpan.setHTML("Dow Jones Industrial");
					var pos = getPosition("^DJI");
					setName(pos, "Dow Jones Industrial");
					var curQuotePrice = data[google.finance.LAST];
					try {			
						curQuotePrice = parseFloat(curQuotePrice.replace(",", ""));
						curQuotePrice = roundNumber(curQuotePrice);
						curQuotePrice = round2Decimals(curQuotePrice);
					}
					catch (e) {
						curQuotePrice = "N/A";
					}
					priceSpan.setHTML(curQuotePrice);
					
					var curQuoteOldPrice = getPrice(pos);
					if (curQuoteOldPrice != "N/A" && curQuotePrice != "N/A" && flashing == 1) {
						curQuoteOldPrice = parseFloat(curQuoteOldPrice);
						if (curQuoteOldPrice > curQuotePrice) {
							row.style.background = "#FF0000";
						} else {
							if (curQuoteOldPrice < curQuotePrice) {
								row.style.background = "#00FF00";
							} else {
								row.style.background = "#FFFFFF";
							}
						}
					}
					setTimeout("javascript:restoreColor('^DJI');", 200);
					setPrice(pos, curQuotePrice);
			
					var curQuoteChange = data[google.finance.CHANGE];
					var curQuotePercentChange = data[google.finance.CHANGE_PCT];
					
					if (isNaN(curQuoteChange)) {
						curQuoteChange = "N/A";
					} else {
						try {
							curQuoteChange = parseFloat(curQuoteChange);
							curQuoteChange = roundNumber(curQuoteChange);
							curQuoteChange = round2Decimals(curQuoteChange);
						} catch (e) {
							curQuoteChange = "N/A";
						}
					}
					setChange(pos, curQuoteChange);
					if (curQuoteChange != 'N/A' && curQuoteChange >= 0) {
						curQuoteChange = "+" + curQuoteChange;
					}
					changeSpan.setHTML(curQuoteChange);
					if (isNaN(curQuotePercentChange)) {
						curQuotePercentChange = "N/A";
					} else {
						curQuotePercentChange = roundNumber(curQuotePercentChange);
						curQuotePercentChange = round2Decimals(curQuotePercentChange);
						if (curQuotePercentChange >= 0) {
							curQuotePercentChange = "+" + curQuotePercentChange;
						}
					}
					setPercentChange(pos, curQuotePercentChange);
					percentSpan.setHTML("(" + curQuotePercentChange + "%)");
					if (parseFloat(curQuotePercentChange) < 0 || parseFloat(curQuoteChange) < 0) {
						changeSpan.style.color = "#990000";
						percentSpan.style.color = "#990000";
					} else if (parseFloat(curQuotePercentChange) > 0 || parseFloat(curQuoteChange) > 0) {
						changeSpan.style.color = "#009900";
						percentSpan.style.color = "#009900";
					} else {
						changeSpan.style.color = "#666666";
						percentSpan.style.color = "#666666";
					}
			
				});
			    
			}
			*/
			
			callServer = function() {
				//getDowData();
			    var symbolArray = getSymbolArray();
			    if (symbolArray.length == 0) {
			        return;
			    }
			    var symbol = "";
			    for (var h = 0; h < symbolArray.length - 1; h++) {
			        symbol += symbolArray[h] + ",";
			    }
			    symbol += symbolArray[h];
			    var newDate = new Date().getTime();
			    //symbol = symbol.replace("^DJI", "INDU");
			    var financeURL = baseURL + symbol + "&f=snl1c1p2&nocache="+newDate;
			    /*
				var params = params || {};
				params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
				params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 60;
				gadgets.io.makeRequest(financeURL, responseText, params);
				*/
				UWA.Data.getText(financeURL, responseText);
			    
			    try {
			        clearTimeout(reloadId);
			    }
			    catch (e) {
			    }    
				if (refreshrate != -1) {
					reloadId = setTimeout("callServer();", refreshrate * 1000);
			    }
			}
			function fixCommas(str) {
			    var x = 0;
			    while (str.indexOf("\"", x) >= 0) {
			        var y = str.indexOf("\"", x);
			        var z = str.indexOf("\"", y + 1);
			        var w = str.indexOf(",", y);
			        if (w > y && w < z) {
			            str = str.substring(0, w) + "." + str.substring(w + 1);
			        }
			        x = z + 1;
			    }
			    return str;
			}
			function responseText(responseString) {
			    var result = responseString;
			    try {
			        var myregexp = new RegExp("\n");
			        var quotes = new Array();
			        quotes = result.split(myregexp);
			        var n59p = 0, n25p = 0, n02p = 0, p25p = 0, p02p = 0, p59p = 0;
			        var n59c = 0, n25c = 0, n02c = 0, p25c = 0, p02c = 0, p59c = 0;
			        var totalGainLoss = 0, portfolioValue = 0;
			        var totalGainLossSpan2 = gel("TotalGainLossSpan2");
			        var portfolioValueSpan2 = gel("PortfolioValueSpan2");
			        for (var c = 0; c < quotes.length; c++) {
			        
				    var curQuote = quotes[c];
			            var curQuoteDetail = fixCommas(curQuote).split(",");
			            var curQuoteTicker = curQuoteDetail[0];
			            curQuoteTicker = getRefinedSymbol(curQuoteTicker);
			            var pos = getPosition(curQuoteTicker);
			            if(pos==-1)
			            	continue;
			        	
			            var symbol = getSymbol(pos);
			            if (symbol == "") {
			                continue;
			            }
			            var nameSpan = gel(getAlphaNumericName(symbol) + "NameSpan");
			            var priceSpan = gel(getAlphaNumericName(symbol) + "PriceSpan");
			            var changeSpan = gel(getAlphaNumericName(symbol) + "ChangeSpan");
			            var percentSpan = gel(getAlphaNumericName(symbol) + "PercentSpan");
			            var tickerSpan = gel(getAlphaNumericName(symbol) + "Span");
			            
			            var tickerSpan2 = gel(getAlphaNumericName(symbol) + "Span2");
			            var gainlossSpan2 = gel(getAlphaNumericName(symbol) + "GainLossSpan2");            
			            
			            var row = gel(getAlphaNumericName(symbol) + "Row");
			            var curQuoteName = curQuoteDetail[1];
			            curQuoteName = getRefinedName(curQuoteName);
			            if (symbol == curQuoteName) {
			                curQuoteName = "Invalid symbol";
			            }
			            curQuoteName = getInitCaps(curQuoteName);
			            nameSpan.setHTML(curQuoteName);
			            if (showname == 0) {
			                tickerSpan.firstChild.setAttribute("title", curQuoteName);
			                tickerSpan2.firstChild.setAttribute("title", curQuoteName);
			            }
			            setName(pos, curQuoteName);
			            var curQuotePrice = removeBold(curQuoteDetail[2]);
			            curQuotePrice = removeImageTag(curQuotePrice);
			            curQuotePrice = removeItalics(curQuotePrice);
			            var curQuoteChange = removeBold(curQuoteDetail[3]);
			            curQuoteChange = removeItalics(curQuoteChange);
			            try {
			                curQuotePrice = parseFloat(curQuotePrice);
			                if (curQuotePrice > 1) {
			                    curQuotePrice = roundNumber(curQuotePrice);
			                    curQuotePrice = round2Decimals(curQuotePrice);
			                }
			            } catch (e) {
			                curQuotePrice = "N/A";
			            }
			            var curQuotePercentChange ="";
			            try {
			            	curQuotePercentChange = curQuoteDetail[4].substring(1, curQuoteDetail[4].length - 2);
			            } catch (e) {
								 curQuotePercentChange = "N/A";
						}
			            curQuotePercentChange = removeBold(curQuotePercentChange);
			            curQuotePercentChange = removeItalics(curQuotePercentChange);
			            curQuotePercentChange = trim(curQuotePercentChange);
			            try {
			                curQuotePercentChange = parseFloat(curQuotePercentChange);
			                if (curQuotePrice > 1) {
			                    curQuotePercentChange = roundNumber(curQuotePercentChange);
			                    curQuotePercentChange = round2Decimals(curQuotePercentChange);
			                }
			            }
			            catch (e) {
			                curQuotePercentChange = "N/A";
			            }
			            priceSpan.setHTML(curQuotePrice);
			            
			            var curQuoteOldPrice = getPrice(pos);
			            if (curQuoteOldPrice != "N/A" && curQuotePrice != "N/A" && flashing == 1) {
			                if (curQuoteOldPrice > curQuotePrice) {
			                    row.setStyle('background-color', '#FF0000');
			                } else {
			                    if (curQuoteOldPrice < curQuotePrice) {
			                        row.setStyle('background-color', '#00FF00');
			                    } else {
			                        row.setStyle('background-color', '#FFFFFF')
			                    }
			                }
			            }
			            setTimeout("javascript:restoreColor('" + symbol + "');", 200);
			            setPrice(pos, curQuotePrice);
			            if (isNaN(curQuoteChange)) {
			                curQuoteChange = "N/A";
			            } else {
			            	try {
							    curQuoteChange = parseFloat(curQuoteChange);
							    if (curQuotePrice > 1 || curQuoteChange==0) {
							        curQuoteChange = roundNumber(curQuoteChange);
							        curQuoteChange = round2Decimals(curQuoteChange);
							    } else {
							        curQuoteChange = Math.round(curQuoteChange * Math.pow(10, 3)) / Math.pow(10, 3);
							    }
			            	} catch (e) {
			                    curQuoteChange = "N/A";
			            	}
			            }
			            setChange(pos, curQuoteChange);
			            if (curQuoteChange != 'N/A' && curQuoteChange >= 0) {
			                curQuoteChange = "+" + curQuoteChange;
			            }
			            changeSpan.setHTML(curQuoteChange);
			            if (isNaN(curQuotePercentChange)) {
			                curQuotePercentChange = "N/A";
			            } else {
			                curQuotePercentChange = roundNumber(curQuotePercentChange);
			                curQuotePercentChange = round2Decimals(curQuotePercentChange);
			                if (curQuotePercentChange >= 0) {
			                    curQuotePercentChange = "+" + curQuotePercentChange;
			                }
			            }
			            if (curQuotePercentChange < -3) {
			                n59c++;
			            } else {
			                if (curQuotePercentChange < -1) {
			                    n25c++;
			                } else {
			                    if (curQuotePercentChange < 0) {
			                        n02c++;
			                    } else {
			                        if (curQuotePercentChange > 3) {
			                            p59c++;
			                        } else {
			                            if (curQuotePercentChange > 1) {
			                                p25c++;
			                            } else {
			                                p02c++;
			                            }
			                        }
			                    }
			                }
			            }
			            setPercentChange(pos, curQuotePercentChange);
			            percentSpan.setHTML("(" + curQuotePercentChange + "%)");
			            if (parseFloat(curQuotePercentChange) < 0 || parseFloat(curQuoteChange) < 0) {
			                changeSpan.setStyle('color', '#990000');
			                percentSpan.setStyle('color', '#990000');
			            } else if (parseFloat(curQuotePercentChange) > 0 || parseFloat(curQuoteChange) > 0) {
			                changeSpan.setStyle('color', '#009900');
			                percentSpan.setStyle('color', '#009900');
			            } else {
			                changeSpan.setStyle('color', '#666666');
			                percentSpan.setStyle('color', '#666666');
			            }
			            
						var gainLossValue = 0;
						var buyPrice = getBuyPrice(pos);
						var numShares = getNumShares(pos);
						if (isNaN(buyPrice))
							buyPrice = 0;
						if (isNaN(numShares))
							numShares = 0;	
						if (isNaN(curQuotePrice))
							curQuotePrice = 0;				
						gainLossValue = (curQuotePrice-buyPrice)*numShares;			
						gainLossValue = roundNumber(gainLossValue);
						gainLossValue = round2Decimals(gainLossValue);
			            gainlossSpan2.setHTML(gainLossValue);
			            if(parseFloat(gainLossValue) < 0)
			            	gainlossSpan2.setStyle('color', '#990000');
			            else if(parseFloat(gainLossValue) > 0)
			            	gainlossSpan2.setStyle('color', '#009900');
						else            	
			            	gainlossSpan2.setStyle('color', '#000000');
			            totalGainLoss = parseFloat(totalGainLoss) + parseFloat(gainLossValue);
			            portfolioValue = parseFloat(portfolioValue) + parseFloat(curQuotePrice*numShares);            
			        }
			        totalGainLoss = roundNumber(totalGainLoss);
			        totalGainLoss = round2Decimals(totalGainLoss);
			        totalGainLossSpan2.setHTML(totalGainLoss);
					if(parseFloat(totalGainLoss) < 0)
						totalGainLossSpan2.setStyle('color', '#990000');
					else if(parseFloat(totalGainLoss) > 0)
						totalGainLossSpan2.setStyle('color', '#009900');
					else            	
						totalGainLossSpan2.setStyle('color', '#000000');        
			
			        portfolioValue = roundNumber(portfolioValue);
			        portfolioValue = round2Decimals(portfolioValue);
			        portfolioValueSpan2.setHTML(portfolioValue);
			        
			        var total = n59c + n25c + n02c + p02c + p25c + p59c;
			        n59p = roundNumber(n59c * 100 / total);
			        n25p = roundNumber(n25c * 100 / total);
			        n02p = roundNumber(n02c * 100 / total);
			        p02p = roundNumber(p02c * 100 / total);
			        p25p = roundNumber(p25c * 100 / total);
			        p59p = roundNumber(p59c * 100 / total);
			        gel("n59").setStyle('width', n59p + "%");
			        gel("n59").setAttributes({title : n59c+" of "+total+" stocks in your watchlist down over 3%"});
			        gel("n25").setStyle('width', n25p + "%");
			        gel("n25").setAttributes({title : n25c+" of "+total+" stocks in your watchlist down between 1% and 3%"});
			        gel("n02").setStyle('width', n02p + "%");
			        gel("n02").setAttributes({title : n02c+" of "+total+" stocks in your watchlist down between 0% and 1%"});
			        gel("p02").setStyle('width', p02p + "%");
			        gel("p02").setAttributes({title : p02c+" of "+total+" stocks in your watchlist up between 0% and 1%"});
			        gel("p25").setStyle('width', p25p + "%");
			        gel("p25").setAttributes({title : p25c+" of "+total+" stocks in your watchlist up between 1% and 3%"});
			        gel("p59").setStyle('width', p59p + "%");
			        gel("p59").setAttributes({title : p59c+" of "+total+" stocks in your watchlist up over 3%"});
			    }
			    catch (e) {
			    }
			    
			}
			
			restoreColor = function(symbol) {
			    var symbolSpan = gel(getAlphaNumericName(symbol) + "Row");
			    symbolSpan.setStyle('background-color', '#FFFFFF');
			}
			function getPrice(c) {
			    return stockTickers[c].price;
			}
			function setPrice(c, newPrice) {
			    stockTickers[c].price = newPrice;
			}
			function setPercentChange(c, newPercent) {
			    stockTickers[c].percent = newPercent;
			}
			function getSymbol(c) {
			    if (c < stockTickers.length) {
			        return stockTickers[c].symbol;
			    } else {
			        return "";
			    }
			}
			function getName(c) {
			    return stockTickers[c].name;
			}
			function setName(c, newName) {
			    stockTickers[c].name = newName;
			}
			function setChange(c, newChange) {
			    stockTickers[c].change = newChange;
			}
			function getNumShares(c) {
			    return stockTickers[c].numshares;
			}
			function getBuyPrice(c) {
			    return stockTickers[c].buyprice;
			}
			function setBuyPrice(c, newBuyPrice) {
			    stockTickers[c].buyprice = newBuyPrice;
			}
			function setNumShares(c, newNumShares) {
			    stockTickers[c].numshares = newNumShares;
			}
			
			function getRefinedSymbol(str) {
			    return str.substring(1, str.length - 1);
			}
			function getRefinedName(str) {
			    return str.substring(1, str.length - 1);
			}
			function trim(str) {
			    return str.replace(/^\s*|\s*$/g, "");
			}
			addStockTicker = function() {
			    gel("myContainer").setHTML(""); 
			    currentSelection=-1;
			
			    var newTickerString = gel("ticker").value;
			    if (newTickerString == "Enter Symbol(s)") {
			        return;
			    }
			    gel("ticker").setAttribute("autocomplete", "off");
			    newTickerString = newTickerString.replace(/ /g, ",");
			    var newTickerArray = newTickerString.split(",");
			    var symbolArray = getSymbolArray();
			
				 // Check for URL too large error
				 if (symbolArray.length == 0) {
				 	 return;
				 }
				 var symbol = "";
				 for (var h = 0; h < symbolArray.length; h++) {
					 symbol += symbolArray[h] + ",";
				 }
			 	 for (var d = 0; d < newTickerArray.length; d++) {
					 symbol += newTickerArray[d] + ",";	
				 }	 
				 if(symbol.length>400) {
				 	 gel("ticker").value = "";
				 	 
					 gel("logger").setHTML("<span style='color:#ff5555'>You have reached the allowable limit on the number of stocks you can add to this gadget. Please delete a few symbols and try adding again..</span>");
					 gel("logger").setStyle('display', '');  
					 
				 	 setTimeout("gel('logger').setHTML('');gel('logger').setStyle('display', 'none');", 5000);
				 	 return;
				 }
			    
				 for (var d = 0; d < newTickerArray.length; d++) {
			        var currentTicker = newTickerArray[d];
			        currentTicker = currentTicker.toUpperCase();
			        if (currentTicker == "") {
			            continue;
			        }
			        var symbolPresent = false;
			        for (var g = 0; g < stockTickers.length; g++) {
			            if (stockTickers[g].symbol == currentTicker) {
			                symbolPresent = true;
			            }
			        }
			        if (symbolPresent) {
			            continue;
			        }
			        stockTickers.push(new StockTicker(currentTicker, "Loading..", "0", "0", "0", "0", "0.00"));
				 }
				 widget.setValue("tickers", convertToString2(stockTickers));
				 stockTickers = sortArray2(stockTickers, sortcol);
				 paintStockTicker();
				 gel("ticker").value = "";
			}
			function paintStockTicker() {
				 if(showNews==1)
				 {
				 	 gel('newsContent').setHTML('Loading news on stocks in your watch list..');
					 gel('newsContent').setStyle('display', '');
					 gel('newsHorLine').setStyle('display', '');
				 }
				 if(showStrength==1)
				 {
				 	 gel('strengthContent').setStyle('display', '');
					 gel('strHorLine').setStyle('display', '');
				 }	 
				 clearTimeout(newsReloadId);
				 callNewsServer();
					
			    var fsize, nameDisplay;
			    if (showname == 1) {
			        fsize = "8";
			        nameDisplay = "";
			    } else {
			        fsize = "9";
			        nameDisplay = "none";
			    }
			    var header = "<table align=center style=\"border:0;  font-family: arial,sans-serif;\" width=\"100%\" id=\"contentTable\" cellspacing=0 cellpadding=0>";
				header+= "<tr>";
				header+="<td align=left>&nbsp;</td>";
				header+="<td align=left style=\"padding-right: 0.5em;\"><a title=\"Click to sort by symbol\" href=\"javascript:void(0);\" onclick=\"javascript:sortByColumn('symbol');\"><font size=\"-1\"><b>Sym</b></font></td>";
				header+="<td align=left style=\"display:" + nameDisplay + "\" ><a title=\"Click to sort by name\" href=\"javascript:void(0);\" onclick=\"javascript:sortByColumn('name');\"><font size=\"-1\"><b>Name</b></a></font></td>";
				header+="<td align=right style=\"padding-right: 0.5em;\"><a title=\"Click to sort by price\" href=\"javascript:void(0);\" onclick=\"javascript:sortByColumn('price');\"><font size=\"-1\"><b>Price</b></a></font></td>";
				header+="<td align=right style=\"padding-right: 0.5em;\"><a title=\"Click to sort by price change\" href=\"javascript:void(0);\" onclick=\"javascript:sortByColumn('change');\"><font size=\"-1\"><b>Chng</b></a></font></td>";
				header+="<td align=right><a title=\"Click to sort by percentage change\" href=\"javascript:void(0);\" onclick=\"javascript:sortByColumn('percent');\"><font size=\"-1\"><b>%Chng</b></a></font></td>";
				header+="</tr>";
			    
			    var footer = "</table>";
			    var contentText = "";
			    for (i = 0; i < stockTickers.length; i++) {
			    	contentText += "<tr id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "Row\" style=\"background:#ffffff;\" onMouseOver=\"highlightColor(this);showChart('" + stockTickers[i].symbol + "')\" onMouseOut=\"unhighlightColor(this);hideChart('" + stockTickers[i].symbol + "')\">";
			        contentText += "<td style=\"padding-right: 3px\" width=\"1%\" align=\"center\" title=\"Delete " + stockTickers[i].symbol + "\"><img src=\""+staticImgUrl+"\" onClick=\"javascript:deleteStockTicker(" + i + ")\"/></td>";
			        contentText += "<td width=\"5%\" align=left style=\"padding-right: 0.5em;\"><font size=\"-1\"><span id=\"" + stockTickers[i].symbol + "Span\"><a href=\"http://finance.yahoo.com/q?s=" + stockTickers[i].symbol + "\" target=\"blank\">" + stockTickers[i].symbol + "</a></span></font></td>";
			        contentText += "<td nowrap style=\"display:" + nameDisplay + "\" width=\"45%\" align=left onClick=\"callMoreData('" + stockTickers[i].symbol + "')\" ><font size=\"-1\"><span style=\"display:" + nameDisplay + "\" id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "NameSpan\">" + stockTickers[i].name + "</span></font></td>";
			        contentText += "<td width=\"20%\" style=\"padding-right: 0.5em;\"align=right onClick=\"callMoreData('" + stockTickers[i].symbol + "')\" ><font size=\"-1\"><span id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "PriceSpan\">" + stockTickers[i].price + "</span></font></td>";
			        contentText += "<td width=\"15%\" style=\"padding-right: 0.5em;\" align=right nowrap onClick=\"callMoreData('" + stockTickers[i].symbol + "')\" ><font size=\"-1\"><span id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "ChangeSpan\">" + stockTickers[i].change + "</span></font></td>";
			        contentText += "<td width=\"15%\" align=right nowrap onClick=\"callMoreData('" + stockTickers[i].symbol + "')\" ><font size=\"-1\"><span id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "PercentSpan\">" + stockTickers[i].percent + "</span></font></td>";
			        contentText += "</tr>";
			        contentText += "<tr><td></td><td></td><td colspan=\"4\" align=\"left\" style=\"width:100%\"><div style=\"position: relative; height: 100%\";><div id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "chartDiv\" style=\"position:absolute;display:none;border:2px double #666666;padding:3px;background:#ffffff;font-size: 8pt;font-family:arial,sans-serif; z-index:3000;\"></div></div></td></tr>";
			    }
			    gel("watchListContent").setHTML(header + contentText + footer);
			    paintPortfolio();
			    try {
			        clearTimeout(reloadId);
			    }
			    catch (e) {
			    }
			    callServer();    
			}
			
			function paintPortfolio() {
			    var fsize, nameDisplay;
			    if (showname == 1) {
			        fsize = "8";
			        nameDisplay = "";
			    } else {
			        fsize = "9";
			        nameDisplay = "none";
			    }	
			    var header = "<table align=center style=\"border:0;  font-family: arial,sans-serif;\" width=\"100%\" cellspacing=0 cellpadding=0>";
				 header+= "<tr>";
				 header+="<td align=left><a href=\"javascript:void(0);\"><font size=\"-1\"><b>Sym</b></font></a></td>";
				 header+="<td align=right><font size=\"-1\"><a href=\"javascript:void(0);\"><b>Qty</b></a></font></td>";
				 header+="<td align=right><font size=\"-1\"><a href=\"javascript:void(0);\"><b>Buy Price</b></a></font></td>";
				 header+="<td align=right><font size=\"-1\"><a href=\"javascript:void(0);\"><b>Gain/Loss</b></a></font></td>";
				 header+="</tr>";
			     
				var footer = "<tr><td colspan=\"4\" align=\"right\"><hr width=\"70%\" align=\"right\"/></td></tr><tr><td width=\"80%\" align=\"right\" colspan=\"3\"><font size=\"-1\">Portfolio Value : <b><span id=\"PortfolioValueSpan2\">0.00</span></font></b></td>	<td width=\"20%\" align=\"right\"><font size=\"-1\"><b><span id=\"TotalGainLossSpan2\">0.00</span><b></font></td></tr></table>";
				var contentText = "";
			
			    for (i = 0; i < stockTickers.length; i++) {
			        contentText += "<tr id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "PortfolioRow\" style=\"background:#ffffff;\" onMouseOver=\"highlightColor(this);\" onMouseOut=\"unhighlightColor(this);\">";
			        contentText += "<td width=\"2%\" align=left><font size=\"-1\"><span id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "Span2\"><a href=\"http://finance.yahoo.com/q?s=" + stockTickers[i].symbol + "\" target=\"blank\">" + stockTickers[i].symbol + "</a></span></font></td>";
			        contentText += "<td width=\"25%\" align=right nowrap onclick='javascript:makeEditable(\""+getAlphaNumericName(stockTickers[i].symbol)+"numshares\", "+i+");' ><font size=\"-1\"><span id=\"span" + getAlphaNumericName(stockTickers[i].symbol) + "numshares\" style=\"display:\" >" + stockTickers[i].numshares + "</span><input type=\"text\" size=\"4\" style=\"text-align:right;display:none\" id=\"text"+getAlphaNumericName(stockTickers[i].symbol)+"numshares\" onblur='javascript:makeUnEditable(\""+getAlphaNumericName(stockTickers[i].symbol)+"numshares\", "+i+",\"numshares\");'></font></td>";
			        contentText += "<td width=\"25%\" align=right nowrap onclick='javascript:makeEditable(\""+getAlphaNumericName(stockTickers[i].symbol)+"buyprice\", "+i+");' ><font size=\"-1\"><span id=\"span" + getAlphaNumericName(stockTickers[i].symbol) + "buyprice\" style=\"display:\" >" + stockTickers[i].buyprice + "</span><input type=\"text\" size=\"4\" style=\"text-align:right;display:none\" id=\"text"+getAlphaNumericName(stockTickers[i].symbol)+"buyprice\" onblur='javascript:makeUnEditable(\""+getAlphaNumericName(stockTickers[i].symbol)+"buyprice\", "+i+",\"buyprice\");'></font></td>";
			        contentText += "<td width=\"25%\" align=right nowrap><font size=\"-1\"><span id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "GainLossSpan2\">0.00</span></font></td>";
			        contentText += "</tr>";        
			    }
			    gel("portfolioContent").setHTML(header + contentText + footer);    
			}
			deleteStockTicker = function(k) {
				var name = getName(k)+' ['+getSymbol(k)+']';
				if(!confirm('Are you sure you want to delete '+name))
					return;
			    stockTickers.splice(k, 1);
			    widget.setValue("tickers", convertToString2(stockTickers));
			    stockTickers = sortArray2(stockTickers, sortcol);
			    paintStockTicker();
			}
			function roundNumber(num) {
			    var rlength = 2;
			    var newnumber = Math.round(num * Math.pow(10, rlength)) / Math.pow(10, rlength);
			    return newnumber;
			}
			highlightColor = function (highlightRow) {
			    highlightRow.style.backgroundColor = '#EEEEFF';
			}
			unhighlightColor = function (highlightRow) {
				highlightRow.style.backgroundColor = '#FFFFFF';
			}
			showChart = function (sym) {
			    if (showchart == 0) {
			        return;
			    }
			    var chartDiv = gel(getAlphaNumericName(sym) + "chartDiv");
			    chartDiv.setHTML("Loading chart..");
			    chartDiv.setStyle('display', '');
			    chartDiv.setHTML("<img src=\"" + cURL + sym + "\">");
			}
			hideChart = function (sym) {
			    if (showchart == 0) {
			        return;
			    }
			    var chartDiv = gel(getAlphaNumericName(sym) + "chartDiv");
			    chartDiv.setStyle('display', 'none');
			    chartDiv.setHTML("Loading chart..");
			
			    gel("logger").setHTML("");
			    gel("logger").setStyle('display', 'none');
			}
			function getPosition(sym) {
				var pos = 0;
				var arr = stockTickers;
				for(var l = 0; l < arr.length; l++) {
					if(arr[l].symbol.toUpperCase()==sym.toUpperCase())
						return (l);
				}
				return -1;
			}
			function showMoreData(responseString, sym) {
				hideAllMoreDivs(stockTickers);
			    var chartDiv = gel(getAlphaNumericName(sym) + "chartDiv");
			    var content = "<table style=\"font-size: 8pt; font-family: arial,sans-serif;\" width=\"100%\">";
			    var results = responseString.split(",");
			    content += "<tr><td align=\"left\"><b>Open</b></td><td align=\"right\">" + results[1] + "</td></tr>";
			    content += "<tr><td align=\"left\"><b>Previous Close</b></td><td align=\"right\">" + results[2] + "</td></tr>";
			    content += "<tr><td align=\"left\"><b>Volume</b></td><td align=\"right\">" + results[3] + "</td></tr>";
			    content += "<tr><td align=\"left\"><b>Days Range</b></td><td align=\"right\">" + formatData(results[4]) + "</td></tr>";
			    content += "<tr><td align=\"left\"><b>52-week Range</b></td><td align=\"right\">" + formatData(results[5]) + "</td></tr>";
			    content += "<tr><td align=\"left\"><b>Last Trade</b></td><td align=\"right\">" + formatData(results[6]) + " EST</td></tr>";
			    content += "<tr><td align=\"left\"><b>Exchange</b></td><td align=\"right\">" + formatData(results[7]) + "</td></tr>";
			    content += "</table>";
			    chartDiv.setHTML("<span style=\"width: 100%; z-index: 1; font-size: 8pt; font-family: arial,sans-serif;\"><table width=\"100%\" style=\"font-size: 8pt; font-family: arial,sans-serif; background-color:#157DEC;\"><tr style=\"color:#FFFFFF;font-weight:bold\"><td align=\"left\" onClick=\"hideMoreDiv('" + sym + "')\">" + joinString(sym, formatData(results[8])) + "</td><td align=\"right\" width=\"5%\" onClick=\"hideMoreDiv('" + sym + "')\">Close</td></tr></table></span>" + content);
			    chartDiv.setStyle('display', '');
				 
				 var position = getPosition(sym);
				 if(position==-1)
				 	position = stockTickers.length;
				 var diff = stockTickers.length-position;
				 if(diff<4 && showNews==0 && showStrength==0) {	 	
				 	gel("logger").setStyle('display', '');
				 	for(var l = 4; l > diff; l--) {
				 		log("");
				 	}
				 }	
			}
			function hideMoreDiv(sym) {
			    var chartDiv = gel(getAlphaNumericName(sym) + "chartDiv");
			    chartDiv.setStyle('display', 'none');
			    chartDiv.setHTML("");    
			    gel("logger").setHTML("");
			    gel("logger").setStyle('display', 'none');
			    
			}
			function hideAllMoreDivs(arr) {
			    for (var l = 0; l < arr.length; l++) {
			        hideMoreDiv(arr[l].symbol);
			    }    
			}
			
			function _IG_Callback(callbackFunction, parameters) {
			  var args = arguments;
			  return function() {
			    var combinedArgs = Array.prototype.slice.call(arguments);
			    callbackFunction.apply(null,
			      combinedArgs.concat(Array.prototype.slice.call(args,1)))
			  }
			}
			
			callMoreData = function(sym) {
			    var chartDiv = gel(getAlphaNumericName(sym) + "chartDiv");
			    chartDiv.setHTML("Loading data..");
			    chartDiv.setStyle('display', '');
			    var newDate = new Date().getTime();
			    var financeURL = baseURL + sym + "&f=sopvmwt1xn&nocache=" + newDate;
			    /*
				var params = params || {};
				params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
				gadgets.io.makeRequest(financeURL, _IG_Callback(showMoreData, sym), params);
				*/
			
				UWA.Data.getText(financeURL, _IG_Callback(showMoreData, sym));
			}
			function formatData(str) {
			    str = str.replace("\n", "").replace("\r", "");
			    if (str.indexOf("\"") == -1) {
			        return str;
			    } else {
			        return str.substring(1, str.length - 1);
			    }
			}
			function round2Decimals(n) {
			    var stringNumber = "" + n;
			    if (stringNumber.indexOf(".") == -1) {
			        stringNumber += ".00";
			    } else {
			        if (stringNumber.substring(stringNumber.indexOf(".") + 1).length == 1) {
			            stringNumber += "0";
			        }
			    }
			    return stringNumber;
			}
			function sortArray(arr) {
			    if (arr.length == 0) {
			        return arr;
			    }
			    var newArray = new Array();
			    var stA = new Array();
			    for (var l = 0; l < arr.length; l++) {
			        stA.push(arr[l].symbol);
			    }
			    stA.sort();
			    for (var h = 0; h < stA.length; h++) {
			        for (var o = 0; o < arr.length; o++) {
			            if (stA[h] == arr[o].symbol) {
			                newArray.push(arr[o]);
			            }
			        }
			    }
			    return newArray;
			}
			
			function sortArray2(tickcopy, col) {
				sortcol = col;
			
				var exp = 'tickers[l].'+col;
			
				var tickers = new Array();
				var nA = new Array();
				var stA = new Array();	
				for(k=0;k<tickcopy.length;k++)
					tickers.push(tickcopy[k]);
			
				for (var l = 0; l < tickers.length; l++) {
					if(parseFloat(eval(exp)))
						stA.push(parseFloat(eval(exp)));
					else
						stA.push(eval(exp));
				}
				if(col=='price' || col=='change' || col=='percent')
				{
					try{
						stA.sort(sortNumber);
					}catch(e) {
						stA.sort();
					}
				}
				else
					stA.sort();
			
				for (var h = 0; h < stA.length; h++) {
					for (var l = 0; l < tickers.length; l++) {
						if(nA.contains(tickers[l]))
							continue;
				
						if(parseFloat(stA[h]))
						{
							if (parseFloat(stA[h]) == parseFloat(eval(exp))) {					
								nA.push(tickers[l]);
							}
						}
						else
						{
							if (stA[h] == eval(exp)) {
								nA.push(tickers[l]);
							}
						}
					}
				}
				tickers = nA;
			
				return tickers;
			
			}
			function sortNumber(a,b)
			{
				if(a-b)
					return a-b;
				else
					return true;
			}
			sortByColumn = function (col)
			{
				stockTickers = sortArray2(stockTickers, col);
				paintStockTicker();
			}
			
			function removeBold(str) {
			    var boldIndexStart = str.indexOf("<b>");
			    var boldIndexEnd = str.lastIndexOf("</b>");
			    if (boldIndexStart == -1) {
			        return str;
			    }
			    var curQuotePrice = str.substring(boldIndexStart + 3, boldIndexEnd);
			    return curQuotePrice;
			}
			function removeItalics(str) {
			    var italicIndexStart = str.indexOf("<i>");
			    var italicIndexEnd = str.lastIndexOf("</i>");
			    if (italicIndexStart == -1) {
			        return str;
			    }
			    var curQuotePrice = str.substring(italicIndexStart + 3, italicIndexEnd);
			    return curQuotePrice;
			}
			function removeImageTag(str) {
				var imgstart = str.indexOf("<img");
			    if (imgstart == -1) {
			        return str;
			    }	
			    var csis = str.indexOf(">", imgstart);
			    var curQuotePrice = str.substring(0,imgstart)+str.substring(csis + 1);
			    return curQuotePrice;
			}
			function dismissMessage(i) {
			    widget.setValue("promo" + i, 1);
			}
			function joinString(a, b) {
			    var onelen = a.length;
			    var twolen = (a.length + b.length > 20) ? (20 - a.length) : b.length;
			    if (twolen != b.length) {
			        b = b.substring(0, twolen) + "..";
			    }
			    var res = b + " (" + a + ")";
			    return res;
			}
			boxFocus = function(val) {
			    var newTickerString = gel("ticker").value;
			    if (val == 0) {
					gel("ticker").setAttribute("autocomplete","off");    
			        if (newTickerString == "Enter Symbol(s)") {
			            gel("ticker").value = "";
			            gel("ticker").setStyle('color', '#000000');
			        }
			    } else {
			        if (newTickerString == "") {
			            gel("ticker").value = "Enter Symbol(s)";
			            gel("ticker").setStyle('color', '#AAAAAA');
			        }
			    }
			}
			function getInitCaps(nt) {
			    var sarr = nt.split(" ");
			    var r = "";
			    for (i = 0; i < sarr.length; i++) {
			        var s = sarr[i].toLowerCase();
			        for (j = 0; j < s.length; j++) {
			            if (j == 0) {
			                r += s.charAt(j).toUpperCase();
			            } else {
			                r += s.charAt(j);
			            }
			        }
			        r += " ";
			    }
			    r = r.substring(0, r.length - 1);
			    return r;
			}
			
			Array.prototype.contains = function(element)   {
				for (var i = 0; i < this.length; i++)
					if (this[i] == element)
						return true;
				return false;
			}
			
			var view = "watchlist";
			toggleView = function() {
				view = gel('view').getHTML().toLowerCase();
				if(view=='portfolio')
				{
					showPortfolio();	
					gel('view').setHTML('Watchlist');
					gel('profitChart').setStyle('display', '');
				}
				else
				{
					showWatchlist();						
					gel('view').setHTML('Portfolio');
					gel('profitChart').setStyle('display', 'none');
					gel('chartContent').setStyle('display', 'none');
					gel('chartHorLine').setStyle('display', 'none');
				}	
				
			}
			
			function showPortfolio()
			{
				gel("portfolioContent").setStyle('display', '');
				gel("watchListContent").setStyle('display', 'none');	
				
			}
			
			function showWatchlist()
			{
				gel("portfolioContent").setStyle('display', 'none');
				gel("watchListContent").setStyle('display', '');	
				
			}
			
			makeEditable = function (objname, i)
			{
				var textObj = gel('text'+objname);
				var spanObj = gel('span'+objname);
			
				textObj.value=spanObj.getHTML();
				spanObj.setStyle('display', 'none');
				textObj.setStyle('display', '');
				textObj.select();
			}
			
			makeUnEditable = function (objname, i, attr)
			{
				var textObj = gel('text'+objname);
				var spanObj = gel('span'+objname);
				if(textObj.value=='')
					textObj.value=0;
			
				var val = textObj.value
				if (!isNaN(val))
				{
					if(val>1||val<=0) {
						val = roundNumber(val);
						if(objname.indexOf('buyprice')!=-1)
							textObj.value = round2Decimals(val);
					}
					spanObj.setHTML(textObj.value);
					textObj.setStyle('display', 'none');
					spanObj.setStyle('display', '');
			
					if(attr=='buyprice')
						setBuyPrice(i, spanObj.getHTML());
					else if(attr=='numshares')
						setNumShares(i, spanObj.getHTML());
					paintStockTicker();
					widget.setValue("tickers", convertToString2(stockTickers));
				} 
			}
				
			showEmailContent = function() {
				if(gel('emailContent').getStyle('display')=='none')
				{
				 gel('emailContent').setStyle('display', '');
				 gel('emailHorLine').setStyle('display', '');	 
				}
				else
				{
				 gel('emailContent').setStyle('display', 'none');
				 gel('emailHorLine').setStyle('display', 'none');	 	
				}
			}
			
			sendEMail = function() {
				if(stockTickers.length<1)
					return;
				var emailSection = gel('emailOption').value;
				var ticks = '';var j=0;
				if(emailSection=='0')
				{	
					for(j=0;j<stockTickers.length-1;j++)
					{
						ticks += stockTickers[j].symbol+', ';
					}
					ticks += stockTickers[j].symbol;
					var sub = 'My Watchlist on Quick Stock Watch';
					var body = 'Hi there, %0A%0AHere are the stocks in my watchlist on Quick Stock Watch : '+ticks+'%0A%0AThanks';
				}
				else
				{
					var tempArr = new Array();
					for(p=0;p<stockTickers.length;p++)
					{
						if(stockTickers[p].numshares!='0')
							tempArr.push(stockTickers[p]);
					}
					if(tempArr.length<1)
						return;				
					for(j=0;j<tempArr.length-1;j++)
					{
						ticks += 'Bought '+tempArr[j].numshares+' shares of '+tempArr[j].symbol+' at '+tempArr[j].buyprice+' - Gain/Loss: '+gel(tempArr[j].symbol+'GainLossSpan2').getHTML()+'%0A';
					}
					ticks += 'Bought '+tempArr[j].numshares+' shares of '+tempArr[j].symbol+' at '+tempArr[j].buyprice+' - Gain/Loss: '+gel(tempArr[j].symbol+'GainLossSpan2').getHTML();
					var sub = 'My Portfolio on Quick Stock Watch';
					var body = 'Hi there, %0A%0AHere is my portfolio on Quick Stock Watch : %0A%0A'+ticks+'%0A%0AThanks';
				}
				window.location='mailto:?subject='+sub+'&body='+body;	
			}
			
			var numResults = 0;
			var currentSelection = -1;
			addEntry = function (symbol)
			{
			  var inputTextObj = gel("ticker");
			  var addedString = "";
			  var inputVal = inputTextObj.value;
			  var commaIndex = inputVal.lastIndexOf(",");
			  
			  if(commaIndex!=-1)
			  {
			    var prevStr = inputVal.substring(0, commaIndex);
			    addedString += prevStr + ", "; 
			  }
			  inputTextObj.value = addedString+symbol+", ";   
			  gel("myContainer").setHTML(""); 
			  currentSelection=-1;
			  if(inputTextObj.createTextRange) {
				  var txtRange = inputTextObj.createTextRange();
				  txtRange.moveStart("character", inputTextObj.value.length);
				  txtRange.moveEnd( "character", 0 );
				  txtRange.select();
			  }
			  else if(inputTextObj.selectionStart) {
			      inputTextObj.focus(); 
			      inputTextObj.setSelectionRange(inputTextObj.value.length, inputTextObj.value.length);  	
			  }
			}
			
			keyEnter = function(e)
			{
			  var key = (window.Event) ? e.which : e.keyCode;
			  switch(key) {
			    case 40: case 38: case 13:
			      return;
			  }
			  currentSelection = -1;
			  numResults = 0;
			  var inputVal = gel("ticker").value;
			  var commaIndex = inputVal.lastIndexOf(",");
			  var prevStr = inputVal.substring(0, commaIndex);
			  var queryStr = inputVal.substring(commaIndex+1);
			  queryStr = trim(queryStr);
			  
			    /*
				var params = params || {};
				params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
				gadgets.io.makeRequest("http://d.yimg.com/autoc.finance.yahoo.com/autoc?query="+_esc(queryStr)+"&callback=YAHOO.Finance.SymbolSuggest.ssCallback",
				*/
				UWA.Data.getText("http://d.yimg.com/autoc.finance.yahoo.com/autoc?query="+escape(queryStr)+"&callback=YAHOO.Finance.SymbolSuggest.ssCallback",
				  function(feed) {  	  
					if (feed == null){ 
						gel("myContainer").setHTML("Error retrieving data");
						return;
				  	}
				  	feed = feed;
					var html = "";
					var res = feed.substring(feed.indexOf('['), feed.lastIndexOf(']')+1);
					var ResultList = eval( res );
					dataArray = eval(res);
					if(dataArray && dataArray.length)
					{
					  numResults  = ResultList.length;
					}
			
					if (ResultList && ResultList.length) {
						html += "<table border='0' cellpadding='2' cellspacing='0' width='99%' style='background-color: #f4f4ff;font-size: 10pt' id='dataTable'>";
						for (var i = 0; i < ResultList.length; i++) {
							var obj =ResultList[i];
							var exchange = obj['type']=='I'?(obj['exchDisp']==undefined?obj['exch']:obj['exchDisp']):obj["exchDisp"]
							if(exchange==undefined)
								exchange="";
							html += "<tr onClick=\"addEntry('"+obj['symbol']+"');\" onMouseOver=\"highlightSuggest(this);\" onMouseOut=\"unhighlightSuggest(this);\">";
							html += "<td align='left' width='30%' id='"+obj['symbol']+"'>"
							 		+ getSelectedStr(obj['symbol'],queryStr)
							 		+ "</td>";
							html += "<td align='left' width='50%'>"
									+ getSelectedStr(obj['name'],queryStr)
									+ "</td>";
							html += "<td align='right' width='20%'>"
									+ exchange
									+ "</td>";
							html += "</tr>";
						}
						html += '</table>';
					}
					gel("myContainer").setHTML(html);
					
				  }); 
			}
			
			keyPress = function (e) {
				var key = (window.Event) ? e.which : e.keyCode;
			    switch(key) {
			    	case 40: case 38:
			    		moveSelection(key);
			    		break;  
			    	case 13:
			    		makeSelection(key);
			    		break; 
			    }
			}
			
			function moveSelection(keyCode) {
				var dataTable = gel("dataTable");
				if(!dataTable)
				  return;
				switch(keyCode) {
			    	case 40:
			    		for(var p=0;p<dataTable.childNodes[0].childNodes.length;p++)
			    			unhighlightSuggest(dataTable.childNodes[0].childNodes[p]);
			    		currentSelection++;
			    		if(currentSelection>numResults-1)
			    			currentSelection = 0;
			    		highlightSuggest(dataTable.childNodes[0].childNodes[currentSelection]);
			    		break;
			    	case 38:
			    		for(var p=0;p<dataTable.childNodes[0].childNodes.length;p++)
			    			unhighlightSuggest(dataTable.childNodes[0].childNodes[p]);
			    		currentSelection--;
			    		if(currentSelection<0)
			    			currentSelection = numResults-1;
			    		highlightSuggest(dataTable.childNodes[0].childNodes[currentSelection]);
			    		break;
				}
			}
			
			function makeSelection(keyCode) {
				var dataTable = gel("dataTable"); 
				if(!dataTable || currentSelection==-1) 
					return; 
				switch(keyCode) { 
			    	case 13: 
			    		addEntry(dataTable.childNodes[0].childNodes[currentSelection].childNodes[0].getAttribute('id'));
			    		break; 
				}
			}
			
			function getSelectedStr(origStr, matchStr)
			{
				var rg = new RegExp("\\b"+matchStr, "ig");
				var finalStr = origStr.replace(rg, "<b>"+origStr.match(rg)+"</b>");
				return finalStr;
			}
			
			highlightSuggest = function (highlightRow) { highlightRow.style.backgroundColor = '#CCCCFF';}
			unhighlightSuggest = function (highlightRow) { highlightRow.style.backgroundColor = '#F4F4FF';}
			
			function log(str) {
			  // gel("logger").setHTML(gel("logger").getHTML() + str+'<br>');
			}
			
			var simpleEncoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
			
			showProfitChart = function() {
			
				gel('chartContent').setHTML('Loading your profit chart.. Please wait..');
				if(gel('chartContent').getStyle('display')=='')
				{
					gel('chartContent').setStyle('display', 'none');
					gel('chartHorLine').setStyle('display', 'none');
						
					return;
				}
				else
				{
					gel('chartContent').setStyle('display', '');
					gel('chartHorLine').setStyle('display', '');
				}
				var chartData = ['s:'];
				var legendData = [''];
				var colorData = [''];
				var amounts = new Array();
				var values = new Array();
				var symbols = new Array();
				var maxValue = 0;
				var maxAmountValue = 0;
				for (var i=0; i<stockTickers.length; i++)
				{
					if(stockTickers[i].numshares==0)
						continue;
					var val = 100*(stockTickers[i].price-stockTickers[i].buyprice)/stockTickers[i].buyprice;		
					val = roundNumber(val);
					val = round2Decimals(val);
					values.push(val);
					symbols.push(stockTickers[i].symbol);
					if(Math.abs(val)>maxValue)
						maxValue = Math.abs(val);
					var amount = stockTickers[i].numshares*stockTickers[i].buyprice;		
					amount = roundNumber(amount);
					amount = round2Decimals(amount);
					amounts.push(amount);
					if(Math.abs(amount)>maxAmountValue)
						maxAmountValue = Math.abs(amount);		
				}
				for (var i=0; i<values.length; i++) {
					var currentValue = amounts[i];
					currentValue = Math.abs(currentValue);
					if (!isNaN(currentValue) && currentValue >= 0) {
						chartData.push(simpleEncoding.charAt(Math.round((simpleEncoding.length-1) * currentValue / maxAmountValue)));
					}
					else {
						chartData.push('_');
					}
					
					if(i==0) {
						legendData.push(symbols[i]+'('+values[i]+'%)');
						if(values[i]<0)
							colorData.push(convertToHex(values[i], maxValue)+'0000');
						else
							colorData.push('00'+convertToHex(values[i], maxValue)+'00');
					}
					else {
						legendData.push('|'+symbols[i]+'('+values[i]+'%)');
						if(values[i]<0)
							colorData.push(','+convertToHex(values[i], maxValue)+'0000');
						else
							colorData.push(','+'00'+convertToHex(values[i], maxValue)+'00');
					}
						
				}
				
				var html = 'You do not have any stocks in your portfolio. Please edit your portfolio by adding the number of shares purchased and price paid for the stocks you own and then try again';
				if(values.length!=0)	
				{
					returnVal = '&chd='+chartData.join('')+'&chl='+legendData.join('')+'&chco='+colorData.join('');
					var url = 'http://chart.apis.google.com/chart?cht=p&chs=320x100&chco=00ff00'+returnVal;
					var imgobj = new Image();
					imgobj.src = url;
					imgobj.onload = function(){
						html = '<img border="0" src="'+imgobj.src+'" alt="Your Portfolio Chart" />';
						gel('chartContent').setHTML(html);	
							
					}
					imgobj.onerror = function(){
						html = 'Sorry, Unable to load your portfolio chart at this time. Please try again later.';
						gel('chartContent').setHTML(html);	
							
					}		
				}
				else
					gel('chartContent').setHTML(html);	
					
			}
			
			function convertToHex(value, maxValue) { 	
				var val = 255-(Math.abs(value)*153/maxValue);	
				return Math.round(val).toString(16);
			}
			
			widget.addEvent('onLoad', initWidget);
			widget.addEvent('onLoad', paintStockTicker); 

        //]]>
        </script>    
    </head>
    <body> 
			<div id="adContent" style="height:60px">
				<script type="text/javascript">
					google_ad_client = "ca-pub-9983113299815649";
					google_ad_slot = "7631094754";
					google_ad_width = 468;
					google_ad_height = 60;
				</script>
				<script type="text/javascript" 
				src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
				</script>		            
			</div>
			
			<div id="watchListContent" style="border:1px solid #FFFFFF; display:;width:100%">Loading your watchlist. Please wait...</div>
			<div id="portfolioContent" style="border:1px solid #FFFFFF; display:none;width:100%">Loading your portfolio. Please wait...</div>
			<form action="javascript:addStockTicker();" style="margin-bottom:5px;">
			<input type="text" value="Enter Symbol(s)" name="ticker" id="ticker" size="12" style="color: #AAAAAA" onfocus="boxFocus(0);" onblur="boxFocus(1);" onkeyup="keyEnter(event);" onkeydown="keyPress(event);"/>
			<input type="button" value="Add" onclick="javascript:addStockTicker();"/>
			&nbsp;&nbsp;<a href="javascript:void(0);" onclick="showStrengthContent();" title="Show/Hide">Strength</a>
			&nbsp;&nbsp;<a href="javascript:void(0);" onclick="showNewsContent();" title="Show/Hide">News</a>
			&nbsp;&nbsp;<a href="http://udaysasi-gadgets.googlecode.com/svn/trunk/quickStockWatchHelp.html">Help</a>
			&nbsp;&nbsp;<a href="javascript:void(0);" onclick="toggleView();"><span id="view">Portfolio</span></a>
			&nbsp;&nbsp;<a href="javascript:void(0);" onclick="showEmailContent();"><span>Email</span></a>
			&nbsp;&nbsp;<a href="http://groups.google.com/group/quickstockwatch">Discuss</a>
			<span id="profitChart" style="display:none">&nbsp;&nbsp;<a href="javascript:void(0);" onclick="showProfitChart();">ProfitChart</a></span>
			&nbsp;&nbsp;<a href="http://udaysasi-gadgets.googlecode.com/svn/trunk/udaysModules.html">My gadgets</a>
			</form>
			<div id="myContainer"></div>
			<hr style="display:none;width:99%"/>
			<table width="99%" id="strengthContent" style="display:none">
				<tbody>
				<tr>
					<td style="width:100%">
						<table style="align:center" border="0" cellpadding="0" cellspacing="0" width="100%">
							<tbody>
							<tr style="height:15px">
								<td id="n59" style="background-color: #992020;width:0%" title=""></td>
								<td id="n25" style="background-color: #CC4949;width:0%" title=""></td>
								<td id="n02" style="background-color: #FF8383;width:0%" title=""></td>
								<td id="p02" style="background-color: #83FF83;width:0%" title=""></td>
								<td id="p25" style="background-color: #49CC49;width:0%" title=""></td>
								<td id="p59" style="background-color: #209920;width:0%" title=""></td>
							</tr>
							</tbody>
						</table>
					</td>
				</tr>
				</tbody>
			</table>
			<hr id="strHorLine" style="display:none;width:99%"/>
			<div id="newsContent" style="text-align:left;border:1px solid #FFFFFF; width:99%; display:none; font-family: arial,sans-serif;"></div>
			<hr id="newsHorLine" style="display:none;width:99%"/>
			
			<div id="emailContent" style="align:left;border:1px solid #FFFFFF; width:99%; display:none; font-family: arial,sans-serif;">
			Send my <select id="emailOption"><option value="0">watchlist</option><option value="1">portfolio</option></select> via e-mail&nbsp;&nbsp;<input type="button" value="Go" onclick="sendEMail();"></input>
			<span>Uses the default e-mail client on your computer.</span>
			</div>
			
			<hr id="emailHorLine" style="display:none;width:99%"/>
			<div id="screenResolutionContent" style="display:none; border:2px solid #157DEC; font-size: 8pt; font-family: arial,sans-serif;"></div>
			<div id="chartContent" style="align:center;border:1px solid #FFFFFF; width:95%; display:none; font-family: arial,sans-serif;">Loading your profit chart.. Please wait..</div>
			<hr id="chartHorLine" style="display:none;width:99%"/>
			<div style="font-family: arial,sans-serif;color:#AAAAAA">(Data and Charts provided by Yahoo! Finance)</div>
			
			<div id="logger" style="display:none"></div>
			
			<script>
			  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
			  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
			  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
			  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
			
			  ga('create', 'UA-1214589-28', 'udaysasi-gadgets.googlecode.com');
			  ga('send', 'pageview');
			
			</script>
    </body>
</html>